#include <HTTP/client/my_client.h>

//String JsonData="{\"BS\":\"1\",\"Msg\":\"成功\",\"total\":0,\"component\":[{\"Name\":\"状态\",\"Value\":\"正常\"},{\"Name\":\"剩余\",\"Value\":\"999\"}],\"url\":null}";

JsonDocument Response;
struct tm timeinfo;
time_t nowSecs;
const char *rootCACertificate = R"string_literal(
-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
-----END CERTIFICATE-----
)string_literal";

static String remove92(String _str) {
  std::string str;
  str=_str.c_str();
  // 使用 std::remove 将所有逗号移到字符串末尾，返回新的逻辑结尾
  auto newEnd = std::remove(str.begin(), str.end(), '\\');
  // 擦除从新逻辑结尾到实际结尾的所有字符
  str.erase(newEnd, str.end());
  str.erase(str.end()-1);
  str.erase(str.begin());
  _str=str.c_str();
  return _str;
  
}

void setClock() 
{
  configTime(0, 0, "ntp.aliyun.com");

  Serial.print(F("Waiting for NTP time sync: "));
  nowSecs = time(nullptr)+60*60*8;
  while (nowSecs < 8 * 3600 * 2) {
    delay(500);
    Serial.print(F("."));
    yield();
    nowSecs = time(nullptr)+60*60*8;
  }

  Serial.println();
  gmtime_r(&nowSecs, &timeinfo);
  Serial.print(F("Current time: "));
  Serial.print(asctime(&timeinfo));
}


void getClock() 
{
  
  nowSecs = time(nullptr)+60*60*8;

  gmtime_r(&nowSecs, &timeinfo);

  //Serial.println(asctime(&timeinfo));
  //Serial.println();

}

time_t* returnClock()
{
  return &nowSecs;
}

int rc_error=-1;/*>Httpcode:返回状态码;-1：访问失败;-3:json反序列化失败*/
int Client_GetDomiTreeElec()
{
  WiFiClientSecure *client = new WiFiClientSecure;
  uint8_t ConnectionFailTimes=0;

  if (client) {
    client->setCACert(rootCACertificate);
    
    // Add a scoping block for HTTPClient https to make sure it is destroyed before NetworkClientSecure *client is
    HTTPClient https;
  
    //Serial.print("[HTTPS] begin...\n");
    if (https.begin(*client, "https://zywxhd02.gxust.edu.cn/Home/GetRoomInfo")) {  // HTTPS
      Serial.print("[HTTPS] POST...\n");
      // start connection and send HTTP header
      https.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
      int httpCode = https.POST("Yzm=123&RoomID=2073");
  
      // httpCode will be negative on error
      if (httpCode > 0) {
        rc_error=httpCode;
        // HTTP header has been send and Server response header has been handled
        //Serial.printf("[HTTPS] POST... code: %d\n", httpCode);
          
        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = https.getString();
          payload=remove92(payload);
          DeserializationError error = deserializeJson(Response, payload); //反序列化JSON数据
          if(!error)
          {
            String RemainingPower=Response["component"][1]["Value"];
            Serial.println("宿舍还剩"+RemainingPower+"度的电");  
              
          }
          else
          {
            rc_error=-3;
          }
      
        }
      } 
      else {
          Serial.printf("[HTTPS] POST... failed, error: %s\n", https.errorToString(httpCode).c_str());         
          rc_error=httpCode;
      }
      https.end();
    } 
    else 
    {
      Serial.printf("[HTTPS] Unable to connect\n");
      ConnectionFailTimes++;
      if(ConnectionFailTimes>=3)
      {
        ConnectionFailTimes=0;
        WiFi.disconnect();
      }
    }
    // End extra scoping block
    delete client;
  } else {
    Serial.println("Unable to create client");
  }
  
  Serial.println("Waiting 10s before the next round...");
  Serial.println();

  return rc_error;
}

String return_msg[2];
String* client_return_elec()
{
  #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
    Serial.println("返回代码："+(String)rc_error);
  #endif
  return_msg[0]=(float)Response["component"][1]["Value"];
  return_msg[1]=rc_error;
  return return_msg;
}

